package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 本类用于
 *
 * @author SJXQ
 * @version 2022/1/18 10:34
 */
@Component
@Slf4j
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;

    }

    @Override
    public int filterOrder() {
        // 第5个过滤器会向RequestContext添加serviceId数据
        // 下面的过滤代码中需要根据这个serviceId来区分访问的服务
        return 6;
    }

    /**
     * 针对当前请求是否执行过滤代码
     *
     * @return true则执行下面的run();
     * false不执行本类定义的过滤方法，直接向后传递
     */
    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
//        System.out.println(JSONObject.toJSON(currentContext));
        final String serviceId = (String) currentContext.get("serviceId");

        return "item-service".equalsIgnoreCase(serviceId);
    }

    /**
     * 过滤代码
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        final HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");


        if (StringUtils.isBlank(token)) {
            // 阻止继续向后调用
            ctx.setSendZuulResponse(false);
            String json = JsonResult.build().code(JsonResult.NOT_LOGIN).toString();
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        // 当前zuul版本中这个返回值不起任何作用
        return null;
    }
}
